// import mqtt from "../../utils/mqtt.min.js";
// import mqtt from "../../utils/mqtt4.2.1.min.js";
import mqtt from "../../utils/mqtt4.1.0.js";

  // ------------------------paho-mqtt-min.js------
  var paho = require("../../utils/paho-mqtt-min.js");
	var client
// git地址：https://github.com/mqttjs/MQTT.js
Page({
  data: {
    client: null,
    conenctBtnText: "连接",
    // host: "wx.emqxcloud.cn",
    // pubTopic: "testtopic/miniprogram",
    // subTopic: "testtopic/miniprogram",
    host: "broker.emqx.io",
    pubTopic: "testtopic",
    subTopic: "testtopic",
    // host: "t.yoyolife.fun",
    // pubTopic: "/iot/5994/device",
    // subTopic: "/iot/5994/device",
    pubMsg: "Hello! I am from WeChat miniprogram",
    receivedMsg: "",
    mqttOptions: {
      clientId: 'emqx_mini_program_' + Math.random().toString(16).substring(2, 8),
      username: "80991fe88ec8804baf69e5d8b418c14c",
      password: "123456",
      reconnectPeriod: 1000, // 1000毫秒，设置为 0 禁用自动重连，两次重新连接之间的间隔时间
      connectTimeout: 30 * 1000, // 30秒，连接超时时间
      // 更多参数请参阅 MQTT.js 官网文档：https://github.com/mqttjs/MQTT.js#mqttclientstreambuilder-options
      // 更多 EMQ 相关 MQTT 使用教程可在 EMQ 官方博客中进行搜索：https://www.emqx.com/zh/blog
    },
  },

  setValue(key, value) {
    this.setData({
      [key]: value,
    });
  },
  setHost(e) {
    this.setValue("host", e.detail.value);
  },
  setSubTopic(e) {
    this.setValue("subTopic", e.detail.value);
  },
  setPubTopic(e) {
    this.setValue("pubTopic", e.detail.value);
  },
  setPubMsg(e) {
    this.setValue("pubMsg", e.detail.value);
  },
  setRecMsg(msg) {
    this.setValue("receivedMsg", msg);
  },

  connect() {
    // MQTT-WebSocket 统一使用 /path 作为连接路径，连接时需指明，但在 EMQX Cloud 部署上使用的路径为 /mqtt
    // 因此不要忘了带上这个 /mqtt !!!
    // 微信小程序中需要将 wss 协议写为 wxs，且由于微信小程序出于安全限制，不支持 ws 协议
    try {
      this.setValue("conenctBtnText", "连接中...");
      const clientId = new Date().getTime();
      this.data.client = mqtt.connect(`wxs://${this.data.host}:8084/mqtt`, {
        ...this.data.mqttOptions,
        clientId,
      });

      this.data.client.on("connect", () => {
        // wx.showToast({
        //   title: "连接成功",
        // });
        console.log('连接成功');
        this.setValue("conenctBtnText", "连接成功");

        this.data.client.on("message", (topic, payload) => {
          // wx.showModal({
          //   content: `收到消息 - Topic: ${topic}，Payload: ${payload}`,
          //   showCancel: false,
          // });
          console.log(`收到消息 - Topic: ${topic}，Payload: ${payload}`);
          const currMsg = this.data.receivedMsg ? `<br/>${payload}` : payload;
          this.setValue("receivedMsg", this.data.receivedMsg.concat(currMsg));
        });

        this.data.client.on("error", (error) => {
          this.setValue("conenctBtnText", "连接");
          console.log("onError", error);
        });

        this.data.client.on("reconnect", () => {
          this.setValue("conenctBtnText", "连接");
          console.log("重连中 reconnecting...");
        });

        this.data.client.on("offline", () => {
          this.setValue("conenctBtnText", "连接");
          console.log("onOffline");
        });
        // 更多 MQTT.js 相关 API 请参阅 https://github.com/mqttjs/MQTT.js#api
      });
    } catch (error) {
      this.setValue("conenctBtnText", "连接");
      console.log("mqtt.connect error", error);
    }
  },

  subscribe() {
    if (this.data.client) {
      this.data.client.subscribe(this.data.subTopic, {qos: 0},function (error) {
        if (!error) {
          console.log('订阅成功');
        }
      });
      // wx.showModal({
      //   content: `成功订阅主题：${this.data.subTopic}`,
      //   showCancel: false,
      // });
      console.log(`成功订阅主题：${this.data.subTopic}`);
      return;
    }
    wx.showToast({
      title: "请先点击连接",
      icon: "error",
    });
  },

  unsubscribe() {
    if (this.data.client) {
      this.data.client.unsubscribe(this.data.subTopic);
      // wx.showModal({
      //   content: `成功取消订阅主题：${this.data.subTopic}`,
      //   showCancel: false,
      // });
      console.log(`成功取消订阅主题：${this.data.subTopic}`);
      return;
    }
    wx.showToast({
      title: "请先点击连接",
      icon: "error",
    });
  },

  publish() {
    if (this.data.client) {
      this.data.client.publish(this.data.pubTopic, this.data.pubMsg);
      return;
    }
    wx.showToast({
      title: "请先点击连接",
      icon: "error",
    });
  },

  disconnect() {
    this.data.client.end();
    this.data.client = null;
    this.setValue("conenctBtnText", "连接");
    wx.showToast({
      title: "成功断开连接",
    });
  },




  // ------------------------paho-mqtt-min.js-----------------
  // git地址：https://github.com/eclipse/paho.mqtt.javascript
  // 官方文档地址：https://www.eclipse.org/paho/files/jsdoc/Paho.MQTT.Client.html/

   /**paho连接,支持发送16进制buffer数据*/
  connectPaho() {
    client = new paho.Client('wss://t.yoyolife.fun/mqtt', 'dfsdwfsdfsd'); //后面这个字符串可以用一个随机字符串方法随机生成
    var connectOptions = {
      //invocationContext: { host: "broker.emqx.io", port: 8084, clientId: 'xcx_wdc_' + util.randomWord(false, 43) },
      timeout: 10,
      //useSSL: true,
      cleanSession: false, //实现QoS>0必须设置为false，代表不清除，是持久会话
      keepAliveInterval: 5,
      reconnect: false, //意外断开之后会重连，第一次1秒后重连，往后每次翻倍直到2分钟，后续保持2分钟
      mqttVersion: 4,
      userName: '',
      password: '',
      onSuccess: function () {
        console.log('连接成功');
        client.onMessageArrived = function (msg) {
          //所有接收的消息都在这里，相关消息的业务处理都写在这里
          var message = this.ab2hex(msg.payloadBytes)
          console.log(message)
        }
        client.subscribe('abc', { qos: 2 });
      },
      onFailure: function (option) {
        console.log('fail', option)
      }
    }
    client.connect(connectOptions)
  },
  //paho发送数据，支持发送16进制buffer
  pahoSend(modbus) {
    var message = new paho.Message(this.string2buffer(modbus))
    message.destinationName = 'abc'
    message.qos = 2
    message.retained = false
    client.send(message)
  },
  /**将ArrayBuffer转换成字符串*/
  ab2hex(buffer){
    var hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
        function (bit) {
          return ('00' + bit.toString(16)).slice(-2)
        }
      )
      return hexArr.join('');
  },
  /**将16进制转化为ArrayBuffer*/
  string2buffer(str){
    return new Uint8Array(str.match(/[\da-f]{2}/gi).map(function (h) {
      return parseInt(h, 16)
    })).buffer
  },
  //切换后台断开
  onHide() {
    client.disconnect()
  },
  //切换前台重连
  onShow() {
    // this.connectPaho()
  },

});